<template>
    <div style="background-color: #041c30">
        <div class="outer-container">
            <div class="search-form-panel">
                <el-form :model="searchData" label-width="120">
                    <el-form-item label="定制查询" prop="type">
                        <el-radio :value="0" v-model="searchData.type" style="width: 20px;"></el-radio>
                    </el-form-item>
                    <el-form-item label="开始时间" prop="valueStart">
                        <el-input-number :min="0" v-model="searchData.valueStart" :disabled="searchData.type === 1"
                            style="width: 100px" />
                        <el-select v-model="searchData.unitStart" style="width: 70px" :disabled="searchData.type === 1">
                            <el-option v-for="(item, index) in TIME_UNIT" :key="index" :value="item.value"
                                :label="item.label"></el-option>
                        </el-select>
                        <span style="margin-left: 4px;">前</span>
                    </el-form-item>
                    <el-form-item label="结束时间" prop="unitEnd">
                        <el-input-number :min="0" v-model="searchData.valueEnd" style="width: 100px"
                            :disabled="searchData.type === 1" />
                        <el-select v-model="searchData.unitEnd" style="width: 70px" :disabled="searchData.type === 1">
                            <el-option v-for="(item, index) in TIME_UNIT" :key="index" :value="item.value"
                                :label="item.label"></el-option>
                        </el-select>
                        <span style="margin-left: 4px;">前</span>
                    </el-form-item>
                    <el-form-item label="数据间隔">
                        <el-input-number :min="0" v-model="searchData.value" style="width: 100px"></el-input-number>
                        <el-select v-model="searchData.unit" style="width: 70px">
                            <el-option v-for="(item, index) in TIME_UNIT" :key="index" :value="item.value"
                                :label="item.label"></el-option>
                        </el-select>
                        <span style="margin-left: 4px;">前</span>
                    </el-form-item>
                    <el-form-item label="最小值">
                        <el-input-number :min="1" v-model="searchData.min" style="width: 140px" />
                    </el-form-item>
                </el-form>
                
                <el-form :model="searchData" label-width="120">
                    <el-form-item label="自定义查询">
                        <el-radio :value="1" v-model="searchData.type" style="width: 20px;"></el-radio>
                    </el-form-item>
                    <el-form-item label="开始时间">
                        <el-config-provider :locale="zhCn">
                            <el-date-picker v-model="timeRange" type="datetimerange" start-placeholder="开始时间"
                                end-placeholder="结束时间" :disabled="searchData.type === 0"
                                :default-time="[initStratTime, initEndTime]" style="width: 476px"
                                format="YYYY-MM-DD HH:mm:ss"/>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="SDZ">
                        <el-select class="sdz-select" v-model="searchData.sdzs" multiple :teleported="false"
                            collapse-tags clearable placeholder="请选择SDZ数据" style="width: 189px">
                            <el-option v-for="(item, index) in sdzOptions" :value="index" :label="item.description"
                                :key="index">
                                {{ item.description }}
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="最大值">
                        <el-input-number :min="1" v-model="searchData.max" style="width: 140px"/>
                    </el-form-item>
                    <el-form-item label="">
                        <el-button type="primary" @click="searchHistoryData">查 询</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="echarts-panel" id="history_echarts">
            </div>
        </div>
    </div>
    <div class="stage_t">
        <a href="#"></a>
        <!-- <h1>智慧燃烧数字化与可视化系统</h1> -->
        <div>
            <span></span>
            <span id="todayTimer">{{ nowTime }}</span>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch } from "vue";
import { formatTime, formatDate } from "../utils/date.js";
import { getSDZlist, history } from "../api/canshushezhi.js";
import * as echarts from "echarts";
import { ElMessage } from 'element-plus'
import { ElConfigProvider } from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'


const nowTime = ref("");

// 获取当前日期
const today = new Date();
// 获取十天前的日期
const initStratTime = new Date(today);
initStratTime.setDate(today.getDate() - 10);

// 将十天前的日期设置为零时
initStratTime.setHours(0, 0, 0, 0);

// 获取今日的日期
const initEndTime = new Date(today);
// 将今日的日期设置为24时
initEndTime.setHours(23, 59, 59, 999);

const timeRange = reactive([initStratTime, initEndTime])

const TIME_UNIT = [
    { value: 'd', label: '天' },
    { value: 'h', label: '时' },
    { value: 'm', label: '分' },
    { value: 's', label: '秒' },
]


let searchData = reactive({
    type: 0, //	默认定制查询0自定义查询1		
    valueStart: 0, //	定制追溯开始时间正整数		
    unitStart: "d", //	默认定制查询开始时间单位秒s分m时h天d，和自定义查询互斥（按钮置灰）		
    valueEnd: 0, //	定制追溯结束时间正整数		
    unitEnd: "d", //	默认定制查询结束时间单位秒s分m时h天d，和自定义查询互斥（按钮置灰）		
    value: 1, //	间隔数值正整数		
    unit: "s", //	查询间隔时间单位秒s分m时h天d		
    min: 0, //	过滤最小值		
    max: 2000, //	过滤最大值		
    sdzs: [],
});

let myChart;

watch(
    () => searchData.sdzs,
    (sdzs, prevSdzs) => {
        if (sdzs.length > 4) {
            nextTick(() => {
                ElMessage({
                    type: 'warning',
                    message: `SDZ最多只能选择4组数据`,
                })
            })
        }
    }
)

onMounted(() => {
    nowTime.value = formatTime(new Date());
    setInterval(() => {
        nowTime.value = formatTime(new Date());
    }, 1000);
    function $(el, all = false) {
        if (all) return document.querySelectorAll(el);
        return document.querySelector(el);
    }
    // 基于准备好的dom，初始化echarts实例
    myChart = echarts.init(document.getElementById("history_echarts"));
    // 请求接口的
    setSdzListData()
});

const sdzOptions = reactive([])

// 设置SDZ数据
const setSdzListData = async () => {
    let sdzRes = await getSDZlist();
    if (sdzRes.status !== 200) {
        return
    }
    sdzOptions.push(...sdzRes.data)
};


// 历史曲线查询
const searchHistoryData = async () => {
    let params = JSON.parse(JSON.stringify(searchData));
    if (params.type === 1) {
        params.startTime = formatDate(timeRange[0])
        params.endTime = formatDate(timeRange[1])
    }
    if (!params.sdzs || params.sdzs.length < 1) {
        ElMessage({
            type: 'warning',
            message: `请选择sdz信息！`,
        })
        return;
    } else if (params.sdzs.length > 4) {
        ElMessage({
            type: 'warning',
            message: `SDZ最多只能选择4组数据`,
        })
        return;
    } else {
        const sdzsTemp = []
        params.sdzs.forEach(i => {
            sdzsTemp.push({
                table0: sdzOptions[i].table0,
                column0: sdzOptions[i].column0,
            })
        })
        params.sdzs = sdzsTemp
    }

    let res = await history(params);
    if (res.status === 200) {
        let xAxisData = [];
        let seriesData = [];
        res.data.forEach(items => {
            if (items && items.length > 0) {
                let avgArr = [];
                let maxArr = [];
                let minArr = [];
                items.forEach(item => {
                    xAxisData.push(item.t);
                    avgArr.push(item.avg);
                    maxArr.push(item.max);
                    minArr.push(item.min);
                })
                seriesData.push({ name: "最小值", type: "line", data: minArr, symbol: "none" })
                seriesData.push({ name: "平均值", type: "line", data: avgArr, symbol: "none" })
                seriesData.push({ name: "最大值", type: "line", data: maxArr, symbol: "none" })
            }
        });
        // 绘制图表
        myChart.setOption({
            textStyle: {
                color: '#FFF',
                fontSize: '16px',
            },
            tooltip: {},
            xAxis: {
                data: xAxisData,
            },
            yAxis: {
                min: 'dataMin', //取最小值为最小刻度
                max: 'dataMax', //取最大值为最大刻度
            },
            legend: {
                textStyle: {
                    color: '#FFF'
                },
                icon: 'rect',
                data: [
                    '最小值',
                    '平均值',
                    '最大值',
                ]
            },
            series: seriesData,
        });
    }
};
</script>







<style lang="scss" scoped>
.outer-container {
    height: 100%;
    min-height: calc(100vh - 55px - 97px);
    margin-top: 55px;
    background-color: #041c30;
    color: #FFF;

    .search-form-panel {
        padding: 20px 100px;
        background-color: #042c45;

        .el-form {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            flex-wrap: wrap;

            &:last-child {
                .el-form-item {
                    margin-bottom: 0;
                }
            }

            .el-form-item {
                margin-bottom: 10px;

                // --el-disabled-bg-color: #cfcfcf;
                &:deep(.el-form-item__label) {
                    --el-text-color-regular: #FFF;
                }
            }

            .sdz-select:deep(.el-select__popper ul.el-scrollbar__view.el-select-dropdown__list) {
                width: 80vw;
                height: 50vh;
                display: flex;
                flex-wrap: wrap;
            }

            .sdz-select:deep(.el-select__popper ul.el-scrollbar__view.el-select-dropdown__list>li) {
                /* width: 200px; */
                flex: 20%;
                border-right: 1px solid #ccc;
            }

            .sdz-select:deep(.el-select-dropdown__wrap) {
                max-height: 50vh;
            }

            .sdz-select:deep(.el-select-dropdown.is-multiple .el-select-dropdown__item.is-selected::after) {
                left: 20px;
                right: unset;
            }

            .sdz-select:deep(.el-select-dropdown.is-multiple .el-select-dropdown__item::before) {
                content: "";
                position: absolute;
                top: 50%;
                border: 1px solid #ccc;
                width: 14px;
                height: 14px;
                left: 18px;
                right: unset;
                border: 1px solid #606266;
                transform: translateY(-50%);
            }

            .sdz-select:deep(.el-select-dropdown__item) {
                padding-left: 40px;
            }
        }
        
    }

    .echarts-panel {
        width: 80%;
        margin: 0 auto;
        height: calc(100vh - 55px - 97px - 150px);
        padding-top: 20px;
    }
}
</style>

<style lang="css">
.stage_t a {
    height: 50px;
}

.stage_t {
    z-index: 1000;
}
</style>
